package com.wish.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.wish.dto.UserDto;
import com.wish.entity.EsSave;
import com.wish.entity.SysUser;
import com.wish.entity.SysUserRole;
import com.wish.mapper.EsMapper;
import com.wish.mapper.SysUserMapper;
import com.wish.service.ISysUserRoleService;
import com.wish.service.ISysUserService;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.wish.vo.ResultEntity;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.elasticsearch.core.ElasticsearchTemplate;
import org.springframework.data.elasticsearch.core.query.IndexQuery;
import org.springframework.data.elasticsearch.core.query.IndexQueryBuilder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;

/**
 * <p>
 * 系统用户 服务实现类
 * </p>
 *
 * @author 五组
 * @since 2021-03-22
 */
@Service
@Slf4j
public class SysUserServiceImpl extends ServiceImpl<SysUserMapper, SysUser> implements ISysUserService {

    @Autowired
    private SysUserMapper sysUserMapper;
    @Autowired
    ISysUserRoleService iSysUserRoleService;
    @Resource
    private ElasticsearchTemplate elasticsearchTemplate;

    @Override
    public List<SysUser> getList(UserDto userDto) {
        List<SysUser> list = sysUserMapper.getList(userDto);
        return list;
    }





    @Override
    @Transactional
    public ResultEntity essave() {
        boolean essave = elasticsearchTemplate.deleteIndex("essave");
        if(!essave){
            return ResultEntity.ok("400","全量同步失败",false);
        }
        List<EsSave> list = sysUserMapper.eslistall();
        for (EsSave es:list) {
            System.out.println(es+"=====");
            IndexQuery query = new IndexQueryBuilder().withId(es.getId() + "").withObject(es).build();
            elasticsearchTemplate.index(query);
        }
        return ResultEntity.ok("200","全量同步成功",true);
    }

    @Override
    public List<SysUser> queryLists(Long deptId, Integer id) {
        return baseMapper.queryLists(deptId,id);
    }

    @Override
    public void updateUser(SysUser user) {
//修改用户表
        this.updateById(user);

        //删除用户和角色的关系
        QueryWrapper<SysUserRole> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("user_id",user.getUserId());
        iSysUserRoleService.remove(queryWrapper);

        //保存用户和角色的关系
        if (user.getRoleId() != null && user.getRoleId().size() > 0) {
            for (Long rid:user.getRoleId()) {
                SysUserRole sysUserRole = new SysUserRole();
                sysUserRole.setUserId(user.getUserId());
                sysUserRole.setRoleId(rid);
                iSysUserRoleService.save(sysUserRole);
            }
        }
    }

}
